var appPath = getAppPath();
var EDIT_IMG_IDX = 0;

$(function(){

	// 检索日期范围
	$("#queryDateStart").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	$("#queryDateEnd").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	
	// 初始化列表
	initOrdersGrid();
	initDetailGrid();
});

function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 订单列表初始化
function initOrdersGrid(){
	
	$('#ordersGrid').datagrid({
	    url:appPath + "/itbOrders/getOrderInfo2Pg.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'order_id',title:'订单ID',width:35,align:'center',sortable:false},
  	        {field:'order_no',title:'订单编号',width:50,align:'center',sortable:false},
		    {field:'downInfo',title:'导出订单',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
  	        		return "<a href='javascript:void(0)' onClick='downOrderInfo("+rowData.order_id+")'>导出</a>";
	        	}
		    },
  	        {field:'user_id',title:'用户ID',width:35,align:'center',sortable:false},
  	        {field:'mobile',title:'用户手机',width:45,align:'center',sortable:false},
	        {field:'detail_cnt',title:'订单明细',width:50,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return "N/A";
	        		var show = '[点击查看] '+(value||'0')+'件';
	        		return "<a href='javascript:void(0)' onClick='showDetail("+rowData.order_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return '<span style="color:red;">N/A</span>';
	        		var show = getState4Show(value);
	        		return "<a href='javascript:void(0)' onClick='editState("+rowData.order_id+")'>"+show+"</a>";
	        	}
		    },
  	        {field:'inv_id',title:'发票ID',width:30,align:'center',sortable:false},
  	        {field:'partner_name',title:'合作方',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pnm = '<span style="color:red;">未设定</span>';
  	        		if(value && value.length>0) {
  	        			pnm = value;
  	        		}
	        		return pnm;
	        	}
		    },
  	        {field:'pay_platform',title:'支付平台',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pf = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: pf="微信"; break;
  	        			case 20: pf="支付宝"; break;
  	        		}
  	        		return pf;
	        	}
		    },
	        {field:'total_fee',title:'订单金额',width:45,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id) return "N/A";
		    		  var show = Number(value||'0')/100;
		    		  return '<span style="color:red;">'+show+'</span>元';
		    	  }
		      },
		    {field:'coupon_id',title:'券ID',width:35,align:'center',sortable:false},
		    {field:'coupon_fee',title:'优惠金额',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id || !rowData.coupon_id) return "";
		    		  var show = Number(value||'0')/100;
		    		  if(show>0) {
		    			  show = '<span style="color:green;">'+show+'</span>';
		    		  }
		    		  return show+'元';
		    	  }
		      },
	        {field:'addr_name',title:'收件人',width:30,align:'center',sortable:false},
		    {field:'addr_id',title:'收件地址',width:50,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
	        		return (rowData.addr_city||'') + ' '+ (rowData.addr_detail||'');
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
		]
	});
}

function initDetailGrid(){
	$('#detailGrid').datagrid({
	    url:appPath + "/itbOrders/getDetailsInfoPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'thumb',title:'商品缩略图',width:50,align:'center',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
	        		var itemThumbs = JSON.parse(rowData.item_thumbs||'[]');
	        		if ( itemThumbs && itemThumbs.length>0 && itemThumbs[0].length>0) {
	        			var showImg = itemThumbs[0]+'?x-oss-process=image/resize,m_pad,h_120,w_120,color_cccccc';
	        			retUrl = '<a href="' + itemThumbs[0] + '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:60px;width:100%">'
	        				+ '<span style="display:table-cell;vertical-align:middle">'
	        				+ '<img src="' +showImg+ '" style="display:inline;max-height:60px;max-width:60px"></span>'
	        				+ '</div></a>';
	        		}
	        		return retUrl;
	        	}
	        },
	        {field:'detail_id',title:'明细ID',width:30,align:'left',sortable:false},
	        {field:'detail_no',title:'明细编号',width:40,align:'left',sortable:false},
	        {field:'item_id',title:'商品ID',width:30,align:'left',sortable:false },
	        {field:'pp_id',title:'套餐ID',width:30,align:'left',sortable:false },
	        {field:'unit',title:'计量单位',width:30,align:'left',sortable:false },
	        {field:'qty',title:'数量',width:35,align:'left',sortable:false },
	        {field:'fee',title:'金额(分)',width:35,align:'left',sortable:false },
	        {field:'tracking_no',title:'运单号',width:48,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.detail_id) return '<span style="color:red;">N/A</span>';
	        		var show = (rowData.express||'')+'['+(value||'NULL')+']';
	        		return "<a href='javascript:void(0)' onClick='editExpress("+rowData.detail_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'user_doc_id',title:'文档ID',width:30,align:'left',sortable:false },
	        {field:'create_time',title:'创建时间',width:30,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:30,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	    
	});
}

function getState4Show(value){
	var state = '<span style="color:red">未知</span>';
	switch(Number(value||'0')){
		case 10: state='<span style="color:blue">待支付</span>'; break;
		case 11: state='<span style="color:green">已支付</span>'; break;
		case 12: state='<span style="color:red">支付失败</span>'; break;
		case 20: state='<span style="color:brown">制作中</span>'; break;
		case 30: state='<span style="color:brown">配送中</span>'; break;
		case 40: state='<span style="color:green">完成</span>'; break;
		case 50: state='<span style="color:red">取消</span>'; break;
	}
	return state;
}

// 状态编辑
function editState(orderId,detailId){
	$("#stateDlg").show();
	$('#stateForm').form('clear');
	$("#updDesc").val('');
	$("#updOrderNo").html('');

	$("#updOrderId").val(orderId);
	$("#updDetailId").val(detailId);
	
	var title = '订单状态';
	var url = appPath + "/itbOrders/getOrdersInfoLst.action?order_id="+ orderId;
	if(Number(detailId||'0')>0){
		title = '订单明细(子订单)状态';
		url = appPath + "/itbOrders/getDetailsInfoLst.action?detail_id="+ detailId;
	}
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#updOrderNo").html(info.order_no||info.detail_no||'');
			$("#updOrderState").combobox('select',info.state||0);
			$("#updDesc").val(info.desc||'');
			$("#updRecdInfo").val(JSON.stringify(info||{}));
		}
	});
	
	$("#stateBtn").show();
	$('#stateDlg').window({
		title: title,
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#stateDlg').window('move',{top:20,left:20});
	$('#stateDlg').window('open');
}
function cancelUpdState(){
	$('#stateDlg').window('close');
}
function doUpdState(){
	var id = $("#updOrderId").val();
	var did = $("#updDetailId").val();
	var state = $("#updOrderState").combobox('getValue');
	var desc = $("#updDesc").val();
	var recdInfo = JSON.parse($("#updRecdInfo").val()||'{}');
	
	// 默认更新订单
	var url = appPath+"/itbOrdersWeb/updOrder.action";
	var sendData = {
		"orderInfo.order_id": Number(id||"0"),
		"orderInfo.state": Number(state || "0"),
		"orderInfo.desc": desc||''
	};
	
	if(Number(did||'0')>0){
		// 更新订单明细
		url = appPath+"/itbOrdersWeb/updDetail.action";
		sendData = {
			"detailInfo.detail_id": Number(did||"0"),
			"detailInfo.state": Number(state || "0"),
			"detailInfo.desc": desc||''
		};
	}
	
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			// 添加历史纪录
			var url2 = appPath+"/itbOrdersWeb/addStateHis.action";
			var sendData2 = {
				"stateHisInfo.type": 10,
				"stateHisInfo.trade_obj_id": Number(did||id||"0"),
				"stateHisInfo.total_fee": recdInfo.fee||recdInfo.total_fee||0,
				"stateHisInfo.user_id": recdInfo.user_id||0,
				"stateHisInfo.state": Number(state || "0"),
				"stateHisInfo.desc": desc||''
			};
			$.post(url2, sendData2, function(data2){
				if(data == "ok") {
					$.messager.alert('提示信息','更新成功','info');
					$('#stateDlg').window('close');
					
					if(Number(did||'0')>0){
						doQuery2();
					} else {
						doQuery();
					}	
				} else {
					$.messager.alert('提示信息','[状态历史]添加失败','info');
				}
			});
					
        } else {
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

// 打开订单明细（子订单）窗口
function showDetail(orderId){
	$('#detailForm').form('clear');
	$("#dtlOrderNo").html('');
	$("#dtlOrderId").val(orderId);
	
	var url = appPath + "/itbOrders/getOrdersInfoLst.action?order_id="+ orderId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#dtlOrderNo").html(info.order_no||'');
			$("#dtlUserId").html(info.user_id||'');
		}
	});
	
	doQuery2();
	
	$("#detailBtn").show();
	$('#detailDlg').window({
		title:'订单明细',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#detailDlg').window('move',{top:20,left:20});
	$('#detailDlg').window('open');
}

function closeDetail(){
	$('#detailDlg').window('close');
}

// 删除订单
function delOrder(){
	var selectItem=$("#ordersGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择订单！','warning');
		return;
	}
	for(var i=0; i<selectItem.length; i++){
		var chk = Number(selectItem[i].state||'0');
		if(chk==20||chk==40||chk==50){
			$.messager.alert('提示信息','不能删除当前状态的订单！','warning');
			return;
		}
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选订单？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.order_id + ",";
				});
				var url = appPath+"/itbOrdersWeb/delOrder.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

// 下载订单信息
function downOrderInfo(orderId){
	
	$.loading(true);
	
	var imgUrl = getApiServer()+"/print/createImageForPrint";
	$.post(imgUrl, {"device":1,"reuse":0/*重新生成*/,"orderId":(orderId||0)}, function(ret){
		if(ret.success==1) {
			var imgLst = ret.data.list||[];
			if(imgLst.length>0){ 
				var downUrl = appPath+"/itbOrdersWeb/downOrderInfo.action";
				//window.open(downUrl);
				$.post(downUrl,{"orderId":(orderId||0),"printImgsInfo":JSON.stringify(imgLst)},function(ret){
					$.loading(false);
					
					if(ret && ret.length>0) {
						var strDate=$.DateUtil.format(new Date(),'yyyyMMddhhmmss');
						var fNm = "ITB_ORDER_INFO_"+strDate+".csv";
						var blob = new Blob([ret]);
						
						var aLink = $('#downA');
						aLink.html(fNm);
						aLink.attr("download", fNm);
						aLink.attr("href", URL.createObjectURL(blob));
						
						$("#downBtn").show();
						$('#downDlg').window({
							title:'订单信息下载',
							iconCls:'icon-save',
							modal: true,
							shadow: true,
							collapsible:false,
							minimizable:false,
							maximizable:false
						});
						$('#downDlg').window('move',{top:20,left:20});
						$('#downDlg').window('open');
						
					} else {
						$.messager.alert('提示信息','数据获取失败','info');
					}
				});
					
			}else{
				$.loading(false);
				$.messager.alert('提示信息','未获取到[印刷用图像文件]','info');
			}
		} else {
			$.loading(false);
			$.messager.alert('提示信息','生成[印刷用图像文件]失败','info');
		}
	});
}
function cancelDown(){
	$('#downDlg').window('close');
}

// 编辑物流信息
function editExpress(dId){
	$("#expressDlg").show();
	$('#expressForm').form('clear');

	$("#expDetailId").val(dId);
	
	var url = appPath + "/itbOrders/getDetailsInfoLst.action?detail_id="+ dId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#expDetailNo").html(info.detail_no||'');
			$("#editExpress").val(info.express||'');
			$("#editTrackNo").val(info.tracking_no||'');
		}
	});
	
	$("#expressBtn").show();
	$('#expressDlg').window({
		title: '订单物流信息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#expressDlg').window('move',{top:20,left:20});
	$('#expressDlg').window('open');
}
function cancelUpdExp(){
	$('#expressDlg').window('close');
}
function doUpdExp(){
	var did = $("#expDetailId").val();
	var express = $("#editExpress").val()||'';
	var trackNo = $("#editTrackNo").val()||'';
	
	if(trackNo.length<=0){
		return $.messager.alert('提示信息','请填写运单号！','warning');
	}
	
	// 默认更新订单
	var url = appPath+"/itbOrdersWeb/updDetail.action";
	var	sendData = {
		"detailInfo.detail_id": Number(did||"0"),
		"detailInfo.express": express||'',
		"detailInfo.tracking_no": trackNo||''
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','更新成功','info');
			$('#expressDlg').window('close');
			doQuery2();			
        } else {
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

/**
 * 获取请求信息(订单列表)
 */
function getQueryParam(){
	var queryObject = {};
	
	//var findType = $("#queryType").combobox('getValue');
	var findState = $("#queryState").combobox('getValue');
	var findPartner = $("#queryPartner").combobox('getValue');
	var findPay= $("#queryPayPf").combobox('getValue');
	var findNo = $("#queryOrderNo").val();
	//var findInvId = $("#queryInvId").val();
	var findMobile = $("#queryMobile").val();
	
	var findDtS = $("#queryDateStart").datebox('getValue');
	var findDtE = $("#queryDateEnd").datebox('getValue');
	
	//if(findType && Number(findType||'0')>0) queryObject.findType = findType;// 分类
	if(findState && Number(findState||'0')>0) queryObject.findState = findState;// 状态
	if(findNo && findNo.length>0) queryObject.findOrderNo = findNo;// 编号
	if(findPartner && Number(findPartner||'0')>0) queryObject.findPartner = findPartner;// 合作方
	if(findPay && Number(findPay||'0')>0) queryObject.findPayPf = findPay;// 支付平台
	//if(findInvId && Number(findInvId||'0')>0) queryObject.findInvId = findInvId;// 发票id
	if(findMobile && Number(findMobile||'0')>0) queryObject.findMobile = findMobile;// 手机号

	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS+' 00:00:00';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59';
	
	return queryObject;
}

/**
 * 获取请求信息(订单详细列表)
 */
function getQueryParam2(){
	var queryObject = {
		findPubFlg: 1,
		findOrderId: Number($("#dtlOrderId").val()||'0')
	};
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	var findDtS = $("#queryDateStart").datebox('getValue');
	var findDtE = $("#queryDateEnd").datebox('getValue');
	if(findDtS && findDtS.length>0){
		var chkRet = chkInputDate(findDtS);
		$("#queryDateStart").datebox('setValue',chkRet);
	}
	if(findDtE && findDtE.length>0){
		var chkRet = chkInputDate(findDtE);
		$("#queryDateEnd").datebox('setValue',chkRet);
	}
	
	$("#ordersGrid").datagrid('unselectAll');
	$("#ordersGrid").datagrid('load', getQueryParam());
}
function doQuery2(){
	$("#detailGrid").datagrid('unselectAll');
	$("#detailGrid").datagrid('load', getQueryParam2());
}

// 判断日期格式[YYYY-MM-DD]
function chkInputDate(dt){
	var strDate=dt+'';
	
    var ss = (strDate.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        var chkDt = new Date(y,m-1,d);
		if((chkDt.getFullYear()==y) &&((chkDt.getMonth()+1)==m) &&(chkDt.getDate()==d)) {
        	return dtFmt(chkDt);
        }
    }
    return '';
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}
